package top.hidoctor.auscultation.feature.activity;

import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.UserManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.tang.user.UserInfoManager;
import com.tang.util.DensityUtil;
import com.tang.util.GsonUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.adapter.ExampleChooseAdapter;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.bean.Sample;
import top.hidoctor.auscultation.bean.UserBean;
import top.hidoctor.auscultation.bean.YangbenBean;
import top.hidoctor.auscultation.event.AddAuditSDEvent;
import top.hidoctor.auscultation.event.AddLabelSDEvent;
import top.hidoctor.auscultation.net.c.ExampleChooseContract;
import top.hidoctor.auscultation.net.c.SampleSearchReq2;
import top.hidoctor.auscultation.net.p.ExampleChoosePresenter;
import top.hidoctor.auscultation.net.req.SampleSearchReq;

public class ExampleChooseActivity extends BaseActivity implements View.OnClickListener, ExampleChooseContract.View {
    private RecyclerView recycler;
    private List<String> list = new ArrayList<>();
    private ExampleChooseAdapter adapter;
    private TextView tvNext;
    private ExampleChoosePresenter presenter;
    private SampleSearchReq req;
    private SwipeRefreshLayout refreshLayout;
    private EditText editSearch;
    private String type; // 1  标注  2 审核
    private SampleSearchReq2 req1;
    private TextView tvTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_example_choose);
        EventBus.getDefault().register(this);
        type = getIntent().getStringExtra("type");
        presenter = new ExampleChoosePresenter(this, this);
        req = new SampleSearchReq("0", "20", 1, UserInfoManager.getInstance().getUserInfo().getHospitalId());
        req1 = new SampleSearchReq2();
        req1.setAuditStatus(0);
        initView();
        initEvent();
    }

    private void initEvent() {
        recycler.setLayoutManager(new GridLayoutManager(ExampleChooseActivity.this, 2));
        recycler.setAdapter(adapter = new ExampleChooseAdapter(R.layout.item_example_choose, null));
        recycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int space = DensityUtil.dip2px(ExampleChooseActivity.this, 10);
                int colums = parent.getChildAdapterPosition(view) % 2;
                outRect.left = colums * space / 2;
                outRect.right = space - (colums + 1) * space / 2;
            }
        });

        adapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                adapter.getData().get(position).setCheck(!adapter.getData().get(position).isCheck());
                adapter.notifyItemChanged(position);
            }
        });
        View view = LayoutInflater.from(this).inflate(R.layout.layout_empty_list, (ViewGroup) recycler.getParent(), false);
        adapter.setEmptyView(view);
        adapter.isFirstOnly(false);
        adapter.openLoadAnimation();
        adapter.openLoadMore(10, true);
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                loadMore();
            }
        });
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                hideSoft(recycler);
                if (type.equals("1")) {
                    req.setKeyWord(editSearch.getText().toString().trim());
                } else {
                    req1.setKeyWord(editSearch.getText().toString().trim());
                }

                refresh();
            }
        });

        editSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                //以下方法防止两次发送请求
                if (actionId == EditorInfo.IME_ACTION_SEND ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    switch (event.getAction()) {
                        case KeyEvent.ACTION_UP:
                            //发送请求
                            if (type.equals("1")) {
                                req.setKeyWord(editSearch.getText().toString().trim());
                            } else {
                                req1.setKeyWord(editSearch.getText().toString().trim());
                            }
                            refresh();
                            return true;
                        default:
                            return true;
                    }
                }
                return false;
            }
        });
        refresh();
    }

    /**
     * 上啦加载
     */
    private void loadMore() {
        req.setPageNo(1 + (type.equals("1") ? req.getPageNo() : req1.getPageNo()));
        if (type.equals("1")) {
            presenter.getYbList(req, refreshLayout);
        } else {
            presenter.getYbList2(req1, refreshLayout);
        }
    }

    /**
     * 下啦刷新
     */
    private void refresh() {
        req.setPageNo(1);
        if (type.equals("1")) {
            presenter.getYbList(req, refreshLayout);
        } else {
            presenter.getYbList2(req1, refreshLayout);
        }
    }

    private void initView() {
        final Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hideSoft(toolbar);
                onBackPressed();
            }
        });
        refreshLayout = findViewById(R.id.refreshLayout);
        editSearch = findViewById(R.id.edit_search);
        recycler = findViewById(R.id.recycler);
        tvNext = findViewById(R.id.tv_next);
        tvTitle = findViewById(R.id.tv_title);
        tvNext.setOnClickListener(this);
        if (type.equals("1")) {
            tvTitle.setText("标注样本选取");
        } else {
            tvTitle.setText("审核样本选取");
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_next:
                List<Sample> checkList = new ArrayList<>();
                for (int i = 0; i < adapter.getData().size(); i++) {
                    if (adapter.getData().get(i).isCheck()) {
                        if (type.equals("1")) {
                            checkList.add(new Sample(adapter.getData().get(i).getId()));
                        } else {
                            checkList.add(new Sample(adapter.getData().get(i).getSampleId()));
                        }
                    }
                }
                if (checkList.size() == 0) {
                    showToast("请选择样本");
                    return;
                }
                if (checkList.size() > 30) {
                    showToast("样本最多选择30个");
                    return;
                }
                startActivity(new Intent(this, RenyuanListActivity.class).putExtra("info", GsonUtil.toJsonStr(checkList)).putExtra("type", type));
                break;
        }
    }

    /**
     * 样本数据回调
     *
     * @param bean
     */
    @Override
    public void getYbListSuc(YangbenBean bean) {
        if (req.getPageNo() == 1) {
            refreshLayout.setRefreshing(false);
            adapter.setNewData(bean.getResult());
        } else {
            adapter.addData(bean.getResult());
        }
        adapter.openLoadMore(bean.getTotalItems() > adapter.getItemCount());
    }

    /**
     * 样本信息回到
     *
     * @param bean
     */
    @Override
    public void getYbListSuc2(YangbenBean bean) {
        if (req1.getPageNo() == 1) {
            refreshLayout.setRefreshing(false);
            adapter.setNewData(bean.getResult());
        } else {
            adapter.addData(bean.getResult());
        }
        adapter.openLoadMore(bean.getTotalItems() > adapter.getItemCount());
    }

    @Override
    public void getUserListSuc(UserBean bean) {

    }

    @Override
    public void addLabelSuc() {

    }

    @Override
    public void addLabelSuc2() {

    }


    @Override
    public void onError(String code, String msg) {
        super.onError(code, msg);
        showToast(msg);
        refreshLayout.setRefreshing(false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AddLabelSDEvent event) {
        finish();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(AddAuditSDEvent event) {
        finish();
    }
}
